package com.baizhi.controller;

import com.baizhi.entity.Banner;
import com.baizhi.service.BannerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2019/4/6.
 */
@Controller
@RequestMapping("/Banner")
public class BannerController {
    @Autowired
    private BannerService bannerService;



    @RequestMapping("/selectAllBanner.do")
    @ResponseBody
    public Map selectAllBanner(int rows,int page,String bannerName){
      return bannerService.selectAllBanner(rows,page,bannerName);
    };


    @RequestMapping("/addBanner.do")
    public @ResponseBody Map addBanner(HttpServletRequest request,Banner banner, MultipartFile bannerImage) throws IOException {
        System.out.println(bannerImage+"222222222222");
        String fileName=bannerImage.getOriginalFilename();
        String st = UUID.randomUUID().toString();
        String newName=st+fileName;
        String realPathNewMethod = request.getServletContext().getRealPath("img");
        try {
            bannerImage.transferTo(new File(realPathNewMethod+"/"+newName));
        } catch (IllegalStateException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        banner.setBannerImageUrl("/img/"+newName);
        return bannerService.addBanner(banner);
    }

    @ResponseBody
    @RequestMapping("/delatebanner.do")
    public Map delateBanner(Integer[] ids){
        return  bannerService.delatebanner(ids);
    }


    @ResponseBody
    @RequestMapping("/updateBanner.do")
    public Map updateBanner(HttpServletRequest request,Banner banner,MultipartFile bannerImage){
        System.out.println("0000000000000");
        if(bannerImage!=null){
            System.out.println("1111111111");
            String fileName=bannerImage.getOriginalFilename();
            String st = UUID.randomUUID().toString();
            String newName=st+fileName;
            String realPathNewMethod = request.getServletContext().getRealPath("img");
            try {
                bannerImage.transferTo(new File(realPathNewMethod+"/"+newName));
            } catch (IllegalStateException | IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            banner.setBannerImageUrl("/img/"+newName);
            return  bannerService.updateBanner(banner);
        }else {
            System.out.println("22222222222");
            return  bannerService.updateBanner(banner);
        }

    }

}
